﻿using A.M.ETO;
using A.M.Storage.Application;
using A.M.Storage.I_Infrastruecure;
using AutoMapper;
using DotNetCore.CAP;
using L.M.System.Application.IServices;
using L.M.System.Domain.DTO;
using L.M.System.Domain.Entity;
using L.M.System.Infrastruecure.IRepository;
using L.M.System.Infrastruecure.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace L.M.System.Application.Services
{
    /// <summary>
    /// 角色实体
    /// </summary>
    public class Role_listServices : BaseServices<role_list, string>, IRole_listServices
    {
        private readonly IStaff_tableServices _staff_tableServices;
        //人员角色表
        private readonly IEmployee_role_tableServices employee_Role_TableServices1;
        //角色主权限
        private readonly IRole_permission_tableServices role_Permission_TableServices;
        //角色二级选线
        private readonly IRole_authorit_listServices role_Authorit_ListServices;
        //权限 + 按钮
        private readonly IRole_button_permissionsServices role_Button_PermissionsServices;
        private readonly IRole_listRepository role_ListRepository;
        private readonly IMapper mapper;
        private readonly ICapPublisher capPublisher;
        //注入员工
        private readonly IStaff_tableServices staff_TableServices;
        //注入员工角色
        private readonly IEmployee_role_tableServices employee_Role_TableServices;
        private readonly IOrganization_chartServices organization_ChartServices;

        public Role_listServices(IRole_listRepository role_ListRepository, IMapper mapper, ICapPublisher capPublisher, IStaff_tableServices staff_TableServices, IEmployee_role_tableServices employee_Role_TableServices, IEmployee_role_tableServices employee_Role_TableServices1, IRole_permission_tableServices role_Permission_TableServices, IRole_authorit_listServices role_Authorit_ListServices = null, IRole_button_permissionsServices role_Button_PermissionsServices = null, IStaff_tableServices staff_tableServices = null, IOrganization_chartServices organization_ChartServices = null) : base(role_ListRepository)
        {
            this.role_ListRepository = role_ListRepository;
            this.mapper = mapper;
            this.capPublisher = capPublisher;
            this.staff_TableServices = staff_TableServices;
            this.employee_Role_TableServices = employee_Role_TableServices;
            this.employee_Role_TableServices1 = employee_Role_TableServices1;
            this.role_Permission_TableServices = role_Permission_TableServices;
            this.role_Authorit_ListServices = role_Authorit_ListServices;
            this.role_Button_PermissionsServices = role_Button_PermissionsServices;
            _staff_tableServices = staff_tableServices;
            this.organization_ChartServices = organization_ChartServices;
        }

        /// <summary>
        /// 角色显示
        /// </summary>
        /// <param name="pageSize">每页条数</param>
        /// <param name="pageIndex">当前页索引</param>
        /// <param name="rName">查询条件</param>
        /// <returns>角色显示</returns>
        public async Task<ApiReturn<PageETO<role_list>>> GteRoleInfor(int pageSize, int pageIndex, string? rName)
        {
            ApiReturn<PageETO<role_list>> apiReturn = new ApiReturn<PageETO<role_list>>();
            Expression<Func<role_list, bool>> i = c => true;
            if (!string.IsNullOrEmpty(rName))
            {
                i = c => c.role_name.Contains(rName);
            }
            var list = await role_ListRepository.GetShowQueryableAsync(pageSize, pageIndex, i);
            list.Data = list.Data.OrderByDescending(c => c.role_date).ToList();
            apiReturn.Code = 200;
            apiReturn.Message = "成功";
            apiReturn.ObjInfor = list;
            return apiReturn;
        }

        /// <summary>
        /// 角色添加
        /// </summary>
        /// <param name="roleAdd">角色实体</param>
        /// <returns>角色</returns>
        public async Task<ApiReturn<string>> GetAddRoelInfor(RoleAddDTO roleAdd)
        {
            ApiReturn<string> apiReturn = new ApiReturn<string>();
            var role = mapper.Map<role_list>(roleAdd);
            role.role_infor = "";
            var res = await role_ListRepository.AddInfor_Async(role);
            if (res > 0)
            {
                apiReturn.Code = 200;
                apiReturn.Message = "添加成功";


                //添加成功需要传一个消息队列  传递哪个模块 还有编号
                string numberName = "岗位管理-" + roleAdd.role_number;
                capPublisher.Publish("GetNewNumber", numberName);
            }
            else
            {
                apiReturn.Code = 500;
                apiReturn.Message = "添加失败";
            }
            return apiReturn;
        }

        /// <summary>
        /// 获取角色下面所有的人员
        /// </summary>
        /// <param name="pageSize">每页条数</param>
        /// <param name="pageIndex">当前页索引</param>
        /// <param name="tName">查询条件</param>
        /// <returns>统一返回格式</returns>
        public async Task<ApiReturn<PageETO<RoleInforEmpInforDTO>>> GetShowRoleTrue(int pageSize, int pageIndex, string? tName)
        {
            ApiReturn<PageETO<RoleInforEmpInforDTO>> apiReturn = new ApiReturn<PageETO<RoleInforEmpInforDTO>>();
            List<RoleInforEmpInforDTO> roleInfor = new List<RoleInforEmpInforDTO>();
            Expression<Func<role_list, bool>> i = e => e.role_status;
            if (!string.IsNullOrEmpty(tName))
            {
                i = e => e.role_name.Contains(tName) && e.role_status;
            }
            var list = await role_ListRepository.GetShowInforAsync(i);

            foreach (var item in list)
            {
                var uname = "";
                int res = 0;
                //获取到角色下面的用户
                var rulist = (await employee_Role_TableServices.GetShowQueryableAsync(c => c.role_number == item.role_number)).ToList();
                foreach (var uitem in rulist)
                {
                    var ulist = staff_TableServices.GetShowObj(c => c.employee_number == uitem.employee_number);
                    if(ulist != null)
                    {
                    uname = uname + ulist.employee_name + "，";

                    }
                    res++;
                }
                roleInfor.Add(new RoleInforEmpInforDTO
                {
                    role_number = item.role_number,
                    rname = item.role_name,
                    ename = uname.TrimEnd('，'),
                    enmnum = res,
                    role_infor = item.role_infor,
                });
            }
            PageETO<RoleInforEmpInforDTO> pageETO = new PageETO<RoleInforEmpInforDTO>();
            pageETO.TotalCount = roleInfor.Count();
            pageETO.PageCount = Convert.ToInt32(Math.Ceiling(roleInfor.Count() * 1.0 / pageSize));
            pageETO.Data = roleInfor.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();
            apiReturn.Code = 200;
            apiReturn.Message = "成功";
            apiReturn.ObjInfor = pageETO;
            return apiReturn;
        }

        /// <summary>
        /// (添加)修改 角色的状态 + 角色主权限添加 + 角色二级权限添加 + 角色按钮添加
        /// </summary>
        /// <param name="roleDTO">角色等权限DTO</param>
        /// <returns>统一返回格式</returns>
        public async Task<ApiReturn<string>> AddInforRole(AddInforRoleDTO roleDTO)
        {
            try
            {
                //开启事务
                role_ListRepository.BeginTranInfor();

                ApiReturn<string> apiReturn = new ApiReturn<string>();
                var res = 0;
                //先启用角色状态
                var rres = role_ListRepository.GetShowObj(c => c.role_number == roleDTO.RId);
                rres.role_status = true;
                rres.role_infor = roleDTO.Rinfor;
                role_ListRepository.UpdInfor(rres);
                if (roleDTO.Ename != "")
                {
                    //添加关联人员
                    var earr = roleDTO.Ename.Split(',');
                    //人员权限关系表
                    List<employee_role_table> employees = new List<employee_role_table>();
                    //清空角色下的的所有人员
                    //await employee_Role_TableServices1.DelInfor_Batch_Async(await employee_Role_TableServices1.GetShowInforAsync(c => c.role_number == roleDTO.RId));
                    foreach (var item in earr)
                    {
                        //清空用户下的所有权限
                        await employee_Role_TableServices1.DelInfor_Batch_Async(await employee_Role_TableServices1.GetShowInforAsync(c => c.employee_number == item));
                        employee_role_table employee = new employee_role_table();
                        employee.employee_role_number = YitIdHelper.NextId().ToString();
                        employee.role_number = roleDTO.RId;
                        employee.employee_number = item;
                        employees.Add(employee);
                    }
                    res += await employee_Role_TableServices1.AddInfor_Batch_Async(employees);
                }



                //删除该角色的一级权限
                await role_Permission_TableServices.DelInfor_Batch_Async(await role_Permission_TableServices.GetShowInforAsync(c => c.role_number == roleDTO.RId));
                //添加角色一级权限
                List<role_permission_table> role_Permissions = new List<role_permission_table>();
                if (roleDTO.Authid != "")
                {
                    var rarr = roleDTO.Authid.Split(',');
                    foreach (var item in rarr)
                    {
                        role_permission_table permission_Table = new role_permission_table();
                        permission_Table.role_authority_number = YitIdHelper.NextId().ToString();
                        permission_Table.role_number = roleDTO.RId;
                        permission_Table.authority_number = item;
                        role_Permissions.Add(permission_Table);
                    }
                    res += await role_Permission_TableServices.AddInfor_Batch_Async(role_Permissions);
                }

                //删除该角色下的二级权限
                await role_Authorit_ListServices.DelInfor_Batch_Async(await role_Authorit_ListServices.GetShowInforAsync(c => c.role_number == roleDTO.RId));
                //角色二级权限
                if (roleDTO.Autelist_id != "")
                {
                    var tarr = roleDTO.Autelist_id.Split(',');
                    List<role_authorit_list> role_authorit_ = new List<role_authorit_list>();
                    foreach (var item in tarr)
                    {
                        role_authorit_list role_Authorit_List = new role_authorit_list();
                        role_Authorit_List.saId = YitIdHelper.NextId().ToString();
                        role_Authorit_List.aid = item;
                        role_Authorit_List.role_number = roleDTO.RId;
                        role_authorit_.Add(role_Authorit_List);
                    }
                    await role_Authorit_ListServices.AddInfor_Batch_Async(role_authorit_);
                }

                //删除该权限下所有的 按钮
                await role_Button_PermissionsServices.DelInfor_Batch_Async(await role_Button_PermissionsServices.GetShowInforAsync(c => c.role_number == roleDTO.RId));
                //添加角色的按钮权限
                if (roleDTO.Bid != "")
                {
                    var bid = roleDTO.Bid.Split(",");
                    List<role_button_permissions> role_button_ = new List<role_button_permissions>();
                    foreach (var item in bid)
                    {
                        role_button_permissions role_Button_Permissions = new role_button_permissions();
                        var arr = item.Split("_");
                        role_Button_Permissions.role_button_number = YitIdHelper.NextId().ToString();
                        role_Button_Permissions.authinfor_number = arr[0];
                        role_Button_Permissions.button_number = arr[1];
                        role_Button_Permissions.role_number = roleDTO.RId;
                        role_button_.Add(role_Button_Permissions);
                    }
                    res += await role_Button_PermissionsServices.AddInfor_Batch_Async(role_button_);
                }

                //提交事务
                role_ListRepository.CommitTranInfor();
                if (res > 3)
                {
                    apiReturn.Code = 200;
                    apiReturn.Message = "添加成功";
                }
                else
                {
                    apiReturn.Code = 500;
                    apiReturn.Message = "添加失败";
                }
                return apiReturn;
            }
            catch (Exception)
            {
                //回滚事务
                role_ListRepository.RollbackTranInfor();
                throw;
            }
        }

        /// <summary>
        /// 获取所有的用户 及 关联的角色
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public async Task<PageETO<Empinfor_roleDTO>> GetStaff_RoleInfor(int pageSize, int pageIndex, string? sName)
        {
            PageETO<Empinfor_roleDTO> pageETO = new PageETO<Empinfor_roleDTO>();
            var erlist = await employee_Role_TableServices.GetShowInforAsync();
            var rlist = await role_ListRepository.GetShowInforAsync();
            var list = (await _staff_tableServices.GetShowInforAsync()).Select(c => new Empinfor_roleDTO
            {
                Eid = c.employee_number,
                Ename = c.employee_name,
            }).Distinct().ToList();
            foreach (var item in list)
            {
                var name = ((from a in erlist
                             join b in rlist
                             on a.role_number equals b.role_number
                             where (item.Eid == a.employee_number)
                             select b).FirstOrDefault());
                if (name != null)
                {
                    item.Rname = name.role_name;
                }
                else
                {
                    item.Rname = "";
                }
            }
            if (!string.IsNullOrEmpty(sName))
            {
                list = list.Where(c => c.Ename.Contains(sName)).ToList();
            }
            pageETO.TotalCount = list.Count();
            pageETO.PageCount = Convert.ToInt32(Math.Ceiling(list.Count() * 1.0 / pageSize));
            pageETO.Data = list.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();
            return pageETO;
        }

        /// <summary>
        /// 获取角色的备注
        /// </summary>
        /// <param name="rId"></param>
        /// <returns>summary</returns>
        public ApiReturn<string> GetRoleInfor(string? rId)
        {
            ApiReturn<string> apiReturn = new ApiReturn<string>();
            var res =  role_ListRepository.GetShowObj(c => c.role_number == rId);
            if(res != null)
            {
                apiReturn.Code = 200;
                apiReturn.Message = res.role_infor;
            }
            else
            {
                apiReturn.Code = 500;
                apiReturn.Message = "";
            }
            return apiReturn;
        }




        /// <summary>
        /// (修改)修改 角色的状态 + 角色主权限添加 + 角色二级权限添加 + 角色按钮添加
        /// </summary>
        /// <param name="roleDTO">角色等权限DTO</param>
        /// <returns>统一返回格式</returns>
        public async Task<ApiReturn<string>> UpdInforRole(AddInforRoleDTO roleDTO)
        {
            try
            {
                //开启事务
                role_ListRepository.BeginTranInfor();

                ApiReturn<string> apiReturn = new ApiReturn<string>();
                var res = 0;
                //先修改角色的备注
                var rres = role_ListRepository.GetShowObj(c => c.role_number == roleDTO.RId);
                rres.role_infor = roleDTO.Rinfor;
                role_ListRepository.UpdInfor(rres);

                //判断关联人员
                    await employee_Role_TableServices1.DelInfor_Batch_Async(await employee_Role_TableServices1.GetShowInforAsync(c => c.role_number == roleDTO.RId));
                if (roleDTO.Ename != "")
                {
                    //添加关联人员
                    var earr = roleDTO.Ename.Split(',');
                    //人员权限关系表
                    List<employee_role_table> employees = new List<employee_role_table>();
                    //清空角色下的的所有人员
                    foreach (var item in earr)
                    {
                        //清空用户下的所有权限
                        await employee_Role_TableServices1.DelInfor_Batch_Async(await employee_Role_TableServices1.GetShowInforAsync(c => c.employee_number == item));
                        employee_role_table employee = new employee_role_table();
                        employee.employee_role_number = YitIdHelper.NextId().ToString();
                        employee.role_number = roleDTO.RId;
                        employee.employee_number = item;
                        employees.Add(employee);
                    }
                    res += await employee_Role_TableServices1.AddInfor_Batch_Async(employees);
                }



                //删除该角色的一级权限
                await role_Permission_TableServices.DelInfor_Batch_Async(await role_Permission_TableServices.GetShowInforAsync(c => c.role_number == roleDTO.RId));
                //添加角色一级权限
                List<role_permission_table> role_Permissions = new List<role_permission_table>();
                if (roleDTO.Authid != "")
                {
                    var rarr = roleDTO.Authid.Split(',');
                    foreach (var item in rarr)
                    {
                        role_permission_table permission_Table = new role_permission_table();
                        permission_Table.role_authority_number = YitIdHelper.NextId().ToString();
                        permission_Table.role_number = roleDTO.RId;
                        permission_Table.authority_number = item;
                        role_Permissions.Add(permission_Table);
                    }
                    res += await role_Permission_TableServices.AddInfor_Batch_Async(role_Permissions);
                }

                //删除该角色下的二级权限
                await role_Authorit_ListServices.DelInfor_Batch_Async(await role_Authorit_ListServices.GetShowInforAsync(c => c.role_number == roleDTO.RId));
                //角色二级权限
                if (roleDTO.Autelist_id != "")
                {
                    var tarr = roleDTO.Autelist_id.Split(',');
                    List<role_authorit_list> role_authorit_ = new List<role_authorit_list>();
                    foreach (var item in tarr)
                    {
                        role_authorit_list role_Authorit_List = new role_authorit_list();
                        role_Authorit_List.saId = YitIdHelper.NextId().ToString();
                        role_Authorit_List.aid = item;
                        role_Authorit_List.role_number = roleDTO.RId;
                        role_authorit_.Add(role_Authorit_List);
                    }
                    await role_Authorit_ListServices.AddInfor_Batch_Async(role_authorit_);
                }

                //删除该权限下所有的 按钮
                await role_Button_PermissionsServices.DelInfor_Batch_Async(await role_Button_PermissionsServices.GetShowInforAsync(c => c.role_number == roleDTO.RId));
                //添加角色的按钮权限
                if (roleDTO.Bid != "")
                {
                    var bid = roleDTO.Bid.Split(",");
                    List<role_button_permissions> role_button_ = new List<role_button_permissions>();
                    foreach (var item in bid)
                    {
                        role_button_permissions role_Button_Permissions = new role_button_permissions();
                        var arr = item.Split("_");
                        role_Button_Permissions.role_button_number = YitIdHelper.NextId().ToString();
                        role_Button_Permissions.authinfor_number = arr[0];
                        role_Button_Permissions.button_number = arr[1];
                        role_Button_Permissions.role_number = roleDTO.RId;
                        role_button_.Add(role_Button_Permissions);
                    }
                    res += await role_Button_PermissionsServices.AddInfor_Batch_Async(role_button_);
                }

                //提交事务
                role_ListRepository.CommitTranInfor();
                if (res > 3)
                {
                    apiReturn.Code = 200;
                    apiReturn.Message = "修改成功";
                }
                else
                {
                    apiReturn.Code = 500;
                    apiReturn.Message = "修改失败";
                }
                return apiReturn;
            }
            catch (Exception)
            {
                //回滚事务
                role_ListRepository.RollbackTranInfor();
                throw;
            }
        }


        /// <summary>
        /// 获取到登录用户的信息
        /// </summary>
        /// <param name="uId">用户编号</param>
        /// <returns>获取到登录用户的信息</returns>
        public async Task<ApiReturn<UserInforDTO>> GetShowStaaInfor(string? uId)
        {
            ApiReturn<UserInforDTO> apiReturn = new ApiReturn<UserInforDTO>();
            var res = await staff_TableServices.GetShowObjAsync(c => c.employee_number == uId);
            if (res == null)
            {
                return null;
            }
            UserInforDTO userInforDTO = new UserInforDTO();
            userInforDTO.staId = res.employee_number;
            userInforDTO.sName = res.employee_name;
            userInforDTO.snumber = res.employee_account;
            userInforDTO.staImage = res.profile_picture;
            userInforDTO.staTel = res.department_tel;
            var getber = await organization_ChartServices.GetShowObjAsync(c => c.department_number == res.department_number);
            if (getber != null)
            {
                userInforDTO.bName = getber.department_name;
            }
            else
            {
                userInforDTO.bName = "";
            }
            var jres = await employee_Role_TableServices.GetShowObjAsync(c => c.employee_number == res.employee_number);
            if (jres != null)
            {
                var jenane = await role_ListRepository.GetShowObjAsync(c => c.role_number == jres.role_number);
                if (jenane != null)
                {
                    userInforDTO.gName = jenane.role_name;
                }
                else
                {
                    userInforDTO.gName = "";
                }
            }
            apiReturn.Code = 200;
            apiReturn.Message = "成功";
            apiReturn.ObjInfor = userInforDTO;
            return apiReturn;
        }

        /// <summary>
        /// 禁用不存在用户的角色
        /// </summary>
        /// <param name="rId">编号</param>
        /// <returns>统一返回格式</returns>
        public async Task<ApiReturn<string>> UpdStaty(string rId)
        {
            ApiReturn<string> apiReturn = new ApiReturn<string>();
            //先判断该角色是否存在
            var res = await role_ListRepository.GetShowObjAsync(c => c.role_number == rId);
            if(res != null)
            {
                //判断该角色是否存在用户
                var srlist = await employee_Role_TableServices1.GetShowQueryableAsync(c => c.role_number == rId);
                if(srlist.Count() > 0)
                {
                    apiReturn.Code = 500;
                    apiReturn.Message = "该角色存在用户，不可禁用";
                    return apiReturn;
                }
                else
                {
                    res.role_status = false;
                    var ges =  await role_ListRepository.UpdInfor_Async(res);
                    if(ges > 0)
                    {
                        apiReturn.Code = 200;
                        apiReturn.Message = "该角色已禁用";
                        return apiReturn;
                    }
                    else
                    {
                        apiReturn.Code = 500;
                        apiReturn.Message = "禁用失败";
                        return apiReturn;
                    }
                }
            }
            else
            {
                apiReturn.Code = 500;
                apiReturn.Message = "请选择要禁用的角色";
                return apiReturn;
            }
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="rId">编号</param>
        /// <returns>统一返回格式</returns>
        public async Task<ApiReturn<string>> DelInforRole(string? rId)
        {
            ApiReturn<string> apiReturn = new ApiReturn<string>();
            //先判断该角色是否存在
            var res = await role_ListRepository.GetShowObjAsync(c => c.role_number == rId);
            if (res != null)
            {
                //判断该角色是否存在用户
                var srlist = await employee_Role_TableServices1.GetShowQueryableAsync(c => c.role_number == rId);
                if (srlist.Count() > 0)
                {
                    apiReturn.Code = 500;
                    apiReturn.Message = "该角色存在用户，不可删除";
                    return apiReturn;
                }
                else
                {
                    res.role_status = false;
                    var ges = await role_ListRepository.DelInfor_Async(res);
                    if (ges > 0)
                    {
                        apiReturn.Code = 200;
                        apiReturn.Message = "删除成功";
                        return apiReturn;
                    }
                    else
                    {
                        apiReturn.Code = 500;
                        apiReturn.Message = "删除失败";
                        return apiReturn;
                    }
                }
            }
            else
            {
                apiReturn.Code = 500;
                apiReturn.Message = "请选择要删除的角色";
                return apiReturn;
            }
        }

        /// <summary>
        /// 反填角色
        /// </summary>
        /// <param name="rId">编号</param>
        /// <returns>统一返回格式</returns>
        public async  Task<ApiReturn<role_list>> FanInforRole(string rId)
        {
            ApiReturn<role_list> apiReturn = new ApiReturn<role_list>();
            var res = await role_ListRepository.GetShowObjAsync(c => c.role_number == rId);
            if(res != null)
            {
                apiReturn.Code = 200;
                apiReturn.Message = "反填成功";
                apiReturn.ObjInfor = res;
            }
            else
            {
                apiReturn.Code = 500;
                apiReturn.Message = "反填失败";
            }
            return apiReturn;
        }

        /// <summary>
        /// 修改角色用户
        /// </summary>
        /// <param name="roleUpd">角色</param>
        /// <returns>修改角色用户</returns>
        public async Task<ApiReturn<string>> GetUpdRoleInfor(RoleAddDTO roleUpd)
        {
            ApiReturn<string> apiReturn = new ApiReturn<string>();
            var res = await role_ListRepository.GetShowObjAsync(c => c.role_number == roleUpd.role_number);
            if(res != null)
            {
                res.role_number = roleUpd.role_number;
                res.role_name = roleUpd.role_name;
                res.role_status = roleUpd.role_status;
                res.role_date = DateTime.Now;
                await role_ListRepository.UpdInfor_Async(res);
                apiReturn.Code = 200;
                apiReturn.Message = "修改成功";
            }
            else
            {
                apiReturn.Code = 500;
                apiReturn.Message = "修改失败";
            }
            return apiReturn;
        }
    }
}
